package com.wgz.medicalmanagement.controller;

import com.wgz.medicalmanagement.common.entity.Result;
import com.wgz.medicalmanagement.domain.dto.ai.ChatHistoryDTO;
import com.wgz.medicalmanagement.service.ChatHistoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天历史控制器
 * 处理与聊天历史记录相关的请求
 */
@Slf4j
@RestController
@RequestMapping("/api/chat-history")
@RequiredArgsConstructor
public class ChatHistoryController {

    private final ChatHistoryService chatHistoryService;

    /**
     * 获取指定会话的聊天记录
     *
     * @param userId    用户ID
     * @param sessionId 会话ID
     * @return 聊天记录
     */
    @GetMapping("/{userId}/{sessionId}")
    public ResponseEntity<Result<ChatHistoryDTO>> getChatHistory(
            @PathVariable Long userId,
            @PathVariable String sessionId) {
        log.info("获取用户 {} 的会话 {} 聊天记录", userId, sessionId);
        
        ChatHistoryDTO chatHistory = chatHistoryService.getChatHistory(userId, sessionId);
        return ResponseEntity.ok(Result.success("获取聊天记录成功", chatHistory));
    }

    /**
     * 获取用户的所有会话
     *
     * @param userId 用户ID
     * @return 会话ID列表
     */
    @GetMapping("/sessions/{userId}")
    public ResponseEntity<Result<List<String>>> getUserSessions(@PathVariable Long userId) {
        log.info("获取用户 {} 的所有会话", userId);
        
        List<String> sessionIds = chatHistoryService.getUserSessionIds(userId);
        return ResponseEntity.ok(Result.success("获取会话列表成功", sessionIds));
    }

    /**
     * 清除指定会话的聊天记录
     *
     * @param userId    用户ID
     * @param sessionId 会话ID
     * @return 操作结果
     */
    @DeleteMapping("/{userId}/{sessionId}")
    public ResponseEntity<Result<Void>> clearChatHistory(
            @PathVariable Long userId,
            @PathVariable String sessionId) {
        log.info("清除用户 {} 的会话 {} 聊天记录", userId, sessionId);
        
        chatHistoryService.clearChatHistory(userId, sessionId);
        return ResponseEntity.ok(Result.success("清除聊天记录成功", null));
    }

    /**
     * 生成新的会话ID
     *
     * @return 新的会话ID
     */
    @PostMapping("/new-session")
    public ResponseEntity<Result<Map<String, String>>> generateNewSession() {
        String sessionId = chatHistoryService.generateSessionId();
        
        Map<String, String> response = new HashMap<>();
        response.put("sessionId", sessionId);
        
        return ResponseEntity.ok(Result.success("生成新会话成功", response));
    }
} 